import React, { Component } from "react";
import { eventTrack, messages } from "share/common";
import { Spin, Radio, Progress, Select, Popover, message } from "antd";
import reportService from "containers/dashboard/dashboard-refactor-comp/report.service";
import "styles/dashboard/dashboard-report.scss";
import Chart from "components/echarts";
import debounce from "lodash.debounce";
import ExampleTag from "containers/home/home-dashboard-share/example-tag";
import WaterMark from "components/water-mark";
import noFeesImg from "images/dashboard/refactor/no-fees.png";
import emptyChartImg from "images/dashboard/refactor/empty-chart.png";
import NullCard from "containers/dashboard/dashboard-component/null-card";
import Chooser from "components/chooser";
import configureStore from "stores";

const RadioGroup = Radio.Group;
const { Option, OptGroup } = Select;
const wrap = "\n";

const deptColumns = [
  {
    title: messages("common-1.key708") /*部门名称*/, //部门名称
    dataIndex: "name",
    width: "67%",
    render: (value, record) => {
      const user = configureStore.store.getState().login.user;
      let ownIdentification = "";
      if (user.departmentOID === record.departmentOid) {
        ownIdentification = messages("common-1.key792") /*(我的)*/;
      }
      const disabledText =
        record.status === 102 ? (
          <span style={{ color: "#B5C0CE" }}>{messages("common-1.key534") /*(已停用)*/}</span>
        ) : (
          ""
        );
      const finalTextNodeName = (
        <span>
          {ownIdentification}
          {record.name}
          {disabledText}
        </span>
      );
      const finalTextNodePath = (
        <span>
          {ownIdentification}
          {record.path}
          {disabledText}
        </span>
      );
      return React.Component.prototype.checkFunctionProfiles("department.full.path.disabled", [undefined, false]) ? (
        <Popover placement="topLeft" content={finalTextNodePath}>
          {finalTextNodePath}
        </Popover>
      ) : (
        <Popover placement="topLeft" content={finalTextNodeName}>
          {finalTextNodeName}
        </Popover>
      );
    },
  },
  {
    title: messages("common-1.key709") /*部门编码*/, //部门编码
    dataIndex: "custDeptNumber",
    width: "33%",
    render: (value) => {
      return (
        <Popover placement="topLeft" content={value || "-"}>
          {value || "-"}
        </Popover>
      );
    },
  },
];

const costColumns = [
  {
    title: messages("basic-5.key533") /*层级*/,
    dataIndex: "levelCode",
    render: (code) => {
      const levelEnumbers = {
        TENANT: messages("basic-5.key534") /*租户*/,
        SET_OF_BOOK: messages("common-1.key425") /*账套*/,
        COMPANY: messages("basic-5.key1") /*公司*/,
      };
      return levelEnumbers[code];
    },
  },
  {
    title: messages("basic-5.key565") /*成本中心项名称*/,
    dataIndex: "name",
    width: "33%",
    render: (value) => {
      return (
        <Popover placement="topLeft" content={value || "-"}>
          {value || "-"}
        </Popover>
      );
    },
  },
  {
    title: messages("basic-5.key61") /*成本中心*/,
    dataIndex: "parentCostCenterName",
    width: "33%",
    render: (value) => {
      return (
        <Popover placement="topLeft" content={value || "-"}>
          {value || "-"}
        </Popover>
      );
    },
  },
  {
    title: messages("basic-5.key564") /*成本中心项编码*/,
    dataIndex: "code",
    width: "33%",
    render: (value) => {
      return (
        <Popover placement="topLeft" content={value || "-"}>
          {value || "-"}
        </Popover>
      );
    },
  },
];

class Report extends Component {
  constructor(props) {
    super(props);
    this.state = {
      emptyChart: false,
      hasPrivilege: false,
      dataLoading: false,
      loading: false,
      privilegeLoading: false,
      privilegeData: undefined,
      overviewData: undefined,
      RadiosGroup: [],
      radioValue: undefined,
      selectValue: undefined,
      selectSetOfBook: undefined,
      options: [],
      currentCurrency: undefined,
      option: undefined,
      setOfBooksOption: [],
      cleanActiveItem: false,
    };
    this.cleanActiveItem = debounce(this.cleanActiveItem, 200);
    this.indexMap = [
      { name: messages("basic-1.key214") /*本月已报销金额*/, key: "totalAmount" },
      { name: messages("basic-1.key118") /*已付款*/, key: "paidTotalAmount" },
      { name: messages("basic-1.key119") /*未付款*/, key: "payingTotalAmount" },
    ];
    this.indexOtherMap = [
      { name: messages("basic-1.key215") /*报销总额*/, key: "totalAmount" },
      { name: messages("basic-1.key216") /*人均报销*/, key: "average" },
      { name: messages("basic-1.key217") /*总人数*/, key: "personNumber" },
    ];
  }

  componentWillMount() {}

  componentDidMount() {
    const { onRef, trialTenant } = this.props;
    onRef && onRef(this);
    if (!trialTenant) {
      this.getPrivilege();
    } else {
      this.setState(
        {
          privilegeData: {},
          RadiosGroup: [{ name: messages("basic-1.key218") /*个人报表*/, key: "personalReportShow" }],
          radioValue: "personalReportShow",
          hasPrivilege: true,
          privilegeLoading: false,
        },
        this.getAllYearData
      );
    }
  }

  setLoading = () => {
    this.setState({ loading: true });
  };

  getRealData = () => {
    this.getPrivilege();
  };

  getPrivilege = () => {
    this.setState({ loading: true, privilegeLoading: true });
    reportService
      .getPrivilege()
      .then((res) => {
        if (res && res.status === 200) {
          const RadiosGroup = [];
          if (res.data.personalReportShow) {
            RadiosGroup.push({ name: messages("basic-1.key218") /*个人报表*/, key: "personalReportShow" });
          }
          if (res.data.departmentReportShow) {
            RadiosGroup.push({ name: messages("basic-1.key219") /*部门报表*/, key: "departmentReportShow" });
          }
          if (res.data.costCenterReportShow) {
            RadiosGroup.push({ name: messages("basic-1.key220") /*成本中心报表*/, key: "costCenterReportShow" });
          }
          const hasPrivilege = !!RadiosGroup.length;
          this.setState(
            {
              privilegeData: res.data,
              RadiosGroup,
              hasPrivilege,
              privilegeLoading: false,
              loading: !(RadiosGroup.length === 0),
              radioValue: RadiosGroup[0] && RadiosGroup[0].key,
            },
            () => {
              this.onRadioChange({ target: { value: RadiosGroup[0] && RadiosGroup[0].key } });
            }
          );
        } else {
          this.setState({ privilegeLoading: false });
        }
      })
      .catch(() => {
        this.setState({ privilegeLoading: false });
      });
  };

  getAllYearData = ({ year, month } = {}, cleanActiveItem = false, onlyQueryDetail = false) => {
    const { trialTenant } = this.props;
    const { radioValue, selectSetOfBook, selectValue, currentCurrency } = this.state;
    const defaultYear = new Date().getFullYear();
    const defaultMonth = new Date().getMonth() + 1;
    const handledMonth = defaultMonth < 10 ? `0${defaultMonth}` : defaultMonth;
    this.setState({ loading: !onlyQueryDetail });
    if (year && month) this.setState({ dataLoading: true });
    const params = {
      year: year || defaultYear,
      month: month || handledMonth,
    };
    if (radioValue === "departmentReportShow") {
      params.setOfBookId = selectSetOfBook;
      params.departmentOID = selectValue && selectValue[0].departmentOID;
    } else {
      params.setOfBookId = selectSetOfBook;
      params.costCenterItemOID = selectValue && selectValue[0].costCenterItemOID;
    }
    reportService
      .getAllYearData(params, radioValue, trialTenant)
      .then((res) => {
        if (res && res.status === 200) {
          if (onlyQueryDetail) {
            this.setState({ overviewData: res.data, loading: false, dataLoading: false });
          } else {
            const option = reportService.createBarOptions({
              data: res.data,
              currency: res.data.baseCurrencyCode || currentCurrency,
              type: radioValue,
            });
            this.setState(
              {
                overviewData: res.data,
                loading: false,
                dataLoading: false,
                option,
                cleanActiveItem,
                emptyChart: false,
              },
              this.cleanActiveItem
            );
          }
        } else {
          this.setState({ loading: false, dataLoading: false });
        }
      })
      .catch(() => {
        this.setState({ loading: false, dataLoading: false });
      });
  };

  cleanActiveItem = () => {
    this.setState({ cleanActiveItem: false });
  };

  renderDetailList = (data) => {
    const { emptyChart } = this.state;
    if (!data && !emptyChart) return <span />;
    if ((data && data.length === 0) || emptyChart)
      return (
        <div className="empty-fees-box">
          <div className="img-box">
            <img src={noFeesImg} className="img" />
          </div>
          <div className="tip">{messages("basic-1.key221") /*本月暂无费用记录*/}</div>
        </div>
      );
    let total = 0;
    data.forEach((item) => {
      total += item.totalAmount;
    });
    return data.map((item) => {
      return (
        <div className="list-fee">
          <div className="img-box">
            <img src={item.iconUrl} className="img" />
          </div>
          <div className="info-box">
            <div className="index-flex">
              <div className="name">{item.expenseTypeName}</div>
              <div className="percent">{((item.totalAmount / total) * 100).toFixed(2)}%</div>
              <div className="amount">{this.filterMoney(item.totalAmount)}</div>
            </div>
            <Progress percent={(item.totalAmount / total) * 100} showInfo={false} />
          </div>
        </div>
      );
    });
  };

  onChartClick = ({ item }) => {
    if (!item) return;
    const newYear = item.name.split("-")[0];
    const newMonth = item.name.split("-")[1];
    this.getAllYearData(
      {
        year: newYear,
        month: newMonth,
      },
      false,
      true
    );
    eventTrack({
      category: "1218-新首页-埋点",
      action: `使用了【图表分析】点击查看了 ${newYear}年${newMonth}月 的费用详情`,
      label: this.props.tenant.tenantName,
    });
  };

  onRadioChange = (e) => {
    const { privilegeData } = this.state;
    const filterCostCenterItem = {};
    let flag = true;
    privilegeData.costCenters &&
      privilegeData.costCenters.map((center) => {
        const currentKey = center.setOfBooksId ? center.setOfBooksId : center.levelCode === "TENANT" ? "TENANT" : null;
        if (!filterCostCenterItem[currentKey]) {
          filterCostCenterItem[currentKey] = [];
          filterCostCenterItem[currentKey].push(center);
        } else {
          filterCostCenterItem[currentKey].push(center);
        }
      });
    let defaultItem;
    if (e.target.value === "costCenterReportShow") {
      try {
        const filterCostCenter =
          filterCostCenterItem[privilegeData.setOfBooks[0].setOfBooksId] || filterCostCenterItem.TENANT;
        defaultItem = [
          {
            costCenterItemOID: filterCostCenter[0].costCenterItems[0].costCenterItemOID,
            name: filterCostCenter[0].costCenterItems[0].name,
          },
        ];
      } catch (err) {
        const data = privilegeData.setOfBooks.find(
          (item) => item.setOfBooksId === privilegeData.setOfBooks[0].setOfBooksId
        );
        message.warn(
          messages("basic-1.key222", { arg1: data.setOfBooksName }) /*【{arg1}】账套下，没有可选成本中心项*/
        );
        flag = false;
      }
    } else if (e.target.value === "departmentReportShow") {
      try {
        defaultItem = [
          {
            fullPath: privilegeData.departments[0].fullPath,
            departmentOID: privilegeData.departments[0].departmentOID,
            name: privilegeData.departments[0].name,
          },
        ];
      } catch (err) {
        message.warn(messages("basic-1.key223") /*无可选部门，请联系管理员*/);
        flag = false;
      }
    }
    this.setState(
      {
        option: undefined,
        overviewData: undefined,
        filterCostCenterItem,
        radioValue: e.target.value,
        setOfBooksOption: privilegeData.setOfBooks,
        selectSetOfBook: privilegeData.setOfBooks[0] && privilegeData.setOfBooks[0].setOfBooksId,
        currentCurrency: privilegeData.setOfBooks[0] && privilegeData.setOfBooks[0].functionalCurrencyCode,
        selectValue: defaultItem,
        options: e.target.value === "departmentReportShow" ? privilegeData.departments : privilegeData.costCenters,
      },
      () => {
        if (flag) this.getAllYearData({}, true);
        else this.setState({ loading: false, emptyChart: true });
      }
    );
  };

  handleSetOfBooksChange = (e) => {
    const { radioValue, filterCostCenterItem, privilegeData } = this.state;
    if (radioValue === "departmentReportShow") {
      let target;
      try {
        target = privilegeData.departments[0].departmentOID;
      } catch (err) {
        message.warn(messages("basic-1.key223") /*无可选部门，请联系管理员*/);
      }
      this.setState(
        {
          selectSetOfBook: e,
          currentCurrency: privilegeData.setOfBooks.find((item) => {
            return item.setOfBooksId === e;
          }).functionalCurrencyCode,
        },
        () => {
          if (target) {
            this.getAllYearData({}, true);
          }
        }
      );
    } else {
      try {
        const filterCostCenter = filterCostCenterItem[e] || filterCostCenterItem.TENANT;
        const defaultItem = {
          costCenterItemOID: filterCostCenter[0].costCenterItems[0].costCenterItemOID,
          name: filterCostCenter[0].costCenterItems[0].name,
        };
        this.setState(
          {
            selectSetOfBook: e,
            selectValue: [defaultItem],
            currentCurrency: privilegeData.setOfBooks.find((item) => {
              return item.setOfBooksId === e;
            }).functionalCurrencyCode,
          },
          () => {
            this.getAllYearData({}, true);
          }
        );
      } catch (err) {
        const data = privilegeData.setOfBooks.find((item) => item.setOfBooksId === e);
        message.warn(
          messages("basic-1.key222", { arg1: data.setOfBooksName }) /*【{arg1}】账套下，没有可选成本中心项*/
        );
      }
    }
  };

  deptService = () => {
    return new Promise((resolve) => {
      resolve({ data: this.state.options, headers: { "x-total-count": this.state.options.length } });
    });
  };

  costService = () => {
    return new Promise((resolve) => {
      const { filterCostCenterItem, selectSetOfBook } = this.state;
      const tenantCostCenter = (filterCostCenterItem && filterCostCenterItem.TENANT) || [];
      const setOfBooksCostCenter = (filterCostCenterItem && filterCostCenterItem[selectSetOfBook]) || [];
      const result = [];
      tenantCostCenter.concat(setOfBooksCostCenter).forEach((center) => {
        center.costCenterItems.forEach((item) => {
          item.parentCostCenterName = center.name;
          item.levelCode = center.levelCode;
          result.push(item);
        });
      });
      resolve({ data: result, headers: { "x-total-count": result.length } });
    });
  };

  render() {
    const {
      loading,
      RadiosGroup,
      option,
      overviewData,
      dataLoading,
      radioValue,
      selectValue,
      options,
      setOfBooksOption,
      selectSetOfBook,
      filterCostCenterItem,
      hasPrivilege,
      privilegeLoading,
      cleanActiveItem,
      emptyChart,
    } = this.state;
    const { trialTenant, onConfirm, uniKey, enableDrag } = this.props;
    const showRadio = RadiosGroup && RadiosGroup.length > 1;
    const indexMap = radioValue === "personalReportShow" ? this.indexMap : this.indexOtherMap;
    const isPersonalReport = radioValue === "personalReportShow";
    const tenantCostCenter = (filterCostCenterItem && filterCostCenterItem.TENANT) || [];
    const setOfBooksCostCenter = (filterCostCenterItem && filterCostCenterItem[selectSetOfBook]) || [];
    return (
      <div id={`home-${uniKey}`} data-id={`home-${uniKey}`} className="dashboard-report full-third-width">
        <Spin spinning={loading}>
          <div className="report-main-box">
            {!trialTenant && hasPrivilege && <WaterMark />}
            <div className="left-chart">
              <div className="home-title">{messages("basic-1.key224") /*图表分析*/}</div>
              {!(privilegeLoading ? true : !hasPrivilege) && (
                <div className="radios">
                  <div className="radio-and-select">
                    {showRadio ? (
                      <RadioGroup onChange={this.onRadioChange} value={radioValue} defaultValue="personalReportShow">
                        {RadiosGroup.map((item) => {
                          return <Radio.Button value={item.key}>{item.name}</Radio.Button>;
                        })}
                      </RadioGroup>
                    ) : (
                      <div>{RadiosGroup[0] && RadiosGroup[0].name}</div>
                    )}

                    {!(radioValue === "personalReportShow") && (
                      <div className="select-box">
                        <Select
                          getPopupContainer={() => document.querySelector(".dashboard-refactor")}
                          onChange={this.handleSetOfBooksChange}
                          value={selectSetOfBook}
                          style={{ width: 150, marginRight: 8 }}
                        >
                          {setOfBooksOption.map((item) => {
                            return (
                              <Option title={item.setOfBooksName} value={item.setOfBooksId}>
                                <Popover placement={"topLeft"} content={item.setOfBooksName}>
                                  {item.setOfBooksName}
                                </Popover>
                              </Option>
                            );
                          })}
                        </Select>
                        <Chooser
                          single
                          onChange={(e) => {
                            this.setState({ selectValue: e }, () => {
                              this.getAllYearData({}, true);
                            });
                          }}
                          showClear={false}
                          labelKey={radioValue === "departmentReportShow" ? "fullPath" : "name"}
                          valueKey={radioValue === "departmentReportShow" ? "departmentOID" : "costCenterItemOID"}
                          value={selectValue}
                          selectorItem={{
                            title:
                              radioValue === "departmentReportShow"
                                ? messages("common-1.key288") /*选择部门*/
                                : messages("basic-5.key608") /*选择成本中心项*/,
                            searchForm: [],
                            columns: radioValue === "departmentReportShow" ? deptColumns : costColumns,
                            key: radioValue === "departmentReportShow" ? "id" : "costCenterItemOID",
                            service: radioValue === "departmentReportShow" ? this.deptService : this.costService,
                          }}
                          chooserClass={"dashboard-report-chooser"}
                        />
                      </div>
                    )}
                  </div>
                </div>
              )}
              {!(privilegeLoading ? true : !hasPrivilege) && (
                <div className="chart-box">
                  {emptyChart ? (
                    <div className="empty-chart">
                      <div className="img-box">
                        <img src={emptyChartImg} className="img" />
                      </div>
                      <div className="tip">{messages("basic-1.key225") /*暂无图表数据*/}</div>
                    </div>
                  ) : (
                    <Chart
                      cleanActiveItem={cleanActiveItem}
                      compareKey={"name"}
                      reportType={"dashboard-histogram"}
                      options={option}
                      height={220}
                      allowActivated
                      onActivatedItemChange={this.onChartClick}
                    />
                  )}
                </div>
              )}
            </div>
            {!(privilegeLoading ? true : !hasPrivilege) && (
              <div className="right-data">
                <Spin spinning={dataLoading}>
                  <div className="index-box">
                    {indexMap.map((item) => {
                      return (
                        <div className="single-index-box">
                          <div className="index-title">{item.name}</div>
                          {item.key === "totalAmount" ? (
                            <div className="index-number-bold">
                              <span style={{ marginRight: 4 }}>{overviewData && overviewData.baseCurrencyCode}</span>
                              {this.filterMoney(overviewData && overviewData[item.key])}
                            </div>
                          ) : (
                            <div className="index-number">
                              {item.key === "average"
                                ? this.filterMoney(overviewData && overviewData.totalAmount / overviewData.personNumber)
                                : this.filterMoney(
                                    isPersonalReport
                                      ? overviewData && overviewData[item.key] && overviewData[item.key].totalAmount
                                      : overviewData && overviewData[item.key],
                                    isPersonalReport ? 2 : 0
                                  )}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                  <div className="detail-box">
                    {this.renderDetailList(overviewData && overviewData.monthlyExpenseOverviewList)}
                  </div>
                </Spin>
              </div>
            )}
            {(privilegeLoading ? false : !hasPrivilege) && (
              <div className={"no-privilege"}>
                <NullCard
                  top={20}
                  imgType={"noReportChart"}
                  message={
                    messages("basic-1.key226", {
                      arg1: wrap,
                    }) /*您当前没有可查看的报表{arg1}如需要，请联系公司管理员添加*/
                  }
                />
              </div>
            )}
          </div>
        </Spin>
        <ExampleTag show={trialTenant} onConfirm={onConfirm} />
        {enableDrag && <div className="toggle-drag-box" />}
      </div>
    );
  }
}

export default Report;
